import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class RelationShipData {

    Configuration configuration =null;
    Connection connection =null;

    @Before
    public void init() throws IOException {
        configuration = HBaseConfiguration.create();
        configuration.set("hbase.zookeeper.quorum","172.17.0.2");
        configuration.set("hbase.zookeeper.property.clientPort","2181");
        connection = ConnectionFactory.createConnection(configuration);
    }

    @Test
    public void createTable() throws IOException {

        HBaseAdmin admin = (HBaseAdmin) connection.getAdmin();

        HTableDescriptor relations = new HTableDescriptor(TableName.valueOf("relations"));

        relations.addFamily(new HColumnDescriptor("friends"));

        admin.createTable(relations);
    }

    @Test
    public void putRelationData() throws IOException {

        Table table = connection.getTable(TableName.valueOf("relations"));

        List<Put> puts = new ArrayList<Put>();
        // rowkey  user1
        Put put12 = new Put(Bytes.toBytes("user1"));
        Put put13 = new Put(Bytes.toBytes("user1"));
        Put put14 = new Put(Bytes.toBytes("user1"));

        put12.addColumn(Bytes.toBytes("friends"),Bytes.toBytes("user2"),Bytes.toBytes("user2"));
        put13.addColumn(Bytes.toBytes("friends"),Bytes.toBytes("user3"),Bytes.toBytes("user3"));
        put14.addColumn(Bytes.toBytes("friends"),Bytes.toBytes("user4"),Bytes.toBytes("user4"));
        puts.add(put12);
        puts.add(put13);
        puts.add(put14);

        // rowkey user2
        Put put21 = new Put(Bytes.toBytes("user2"));
        Put put23 = new Put(Bytes.toBytes("user2"));

        put21.addColumn(Bytes.toBytes("friends"),Bytes.toBytes("user1"),Bytes.toBytes("user1"));
        put23.addColumn(Bytes.toBytes("friends"),Bytes.toBytes("user3"),Bytes.toBytes("user3"));
        puts.add(put21);
        puts.add(put23);
        table.put(puts);

        table.close();
    }

    @After
    public void release(){
        if(connection!=null){
            try {
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
